<template>
    <div class="workbench">
        <div class="lg:flex">
            <el-card class="!border-none mb-4 flex-1 p-4" shadow="never">
                <template #header>
                    <div class="mb-2.5">
                        <div class="flex items-center">
                            <div class="card-title">今日实时数据</div>
                            <el-select-v2
                                v-model="area_id"
                                filterable
                                clearable
                                :options="optionCity"
                                placeholder="请选择"
                                class="w-[140px] ml-2.5"
                                style="width: 100px"
                                @change="onChange"
                            />
                        </div>
                        
                        <div class="text-tx-secondary text-xs flex items-center">
                            <span v-if="isPc" class="text-circle mr-2"></span>数据时间：{{ workbenchData.today.time }}
                        </div>
                    </div>
                </template>

                <div class="flex flex-wrap justify-between">
                    <div class=" md:w-1/7">
                        <div class="leading-2.5">注册新用户数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.today_statistic.today_reg_user_num }}
                            <!-- <span class="text-xs font-normal ml-1">人</span> -->
                        </div>
                        <div class="text-tx-secondary text-xs">
                            <span>较昨日</span>
                            <span class="up" v-if="workbenchData.today_statistic.yesterday_today_reg_user_rate >= 0">{{ `+${(workbenchData.today_statistic.yesterday_today_reg_user_rate * 10000 / 100).toFixed(2)}%` }}</span>
                            <span class="down" v-else>{{ `${(workbenchData.today_statistic.yesterday_today_reg_user_rate * 10000 / 100).toFixed(2) }%` }}</span>
                        </div>
                    </div>
                    <div class=" md:w-1/7">
                        <div class="leading-2.5">活跃用户数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.today_statistic.today_ac_user_num }}
                            <!-- <span class="text-xs font-normal ml-1">人</span> -->
                        </div>
                        <div class="text-tx-secondary text-xs">
                            <span>较昨日</span>
                            <span class="up" v-if="workbenchData.today_statistic.yesterday_today_ac_user_rate >= 0">{{ `+${(workbenchData.today_statistic.yesterday_today_ac_user_rate * 10000 / 100).toFixed(2)}%` }}</span>
                            <span class="down" v-else>{{ `${(workbenchData.today_statistic.yesterday_today_ac_user_rate * 10000 / 100).toFixed(2) }%` }}</span>
                        </div>
                    </div>
                    <div class=" md:w-1/7">
                        <div class="leading-2.5">活跃渠道数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.today_statistic.today_ac_channel_num }}
                            <!-- <span class="text-xs font-normal ml-1">人</span> -->
                        </div>
                        <div class="text-tx-secondary text-xs">
                            <span>较昨日</span>
                            <span class="up" v-if="workbenchData.today_statistic.yesterday_today_ac_channel_rate >= 0">{{ `+${(workbenchData.today_statistic.yesterday_today_ac_channel_rate * 10000 / 100).toFixed(2)}%` }}</span>
                            <span class="down" v-else>{{ `${(workbenchData.today_statistic.yesterday_today_ac_channel_rate * 10000 / 100).toFixed(2) }%` }}</span>
                        </div>
                    </div>
                    <div class=" md:w-1/7">
                        <div class="leading-2.5">合作单数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.today_statistic.today_cooperation_num }}
                            <!-- <span class="text-xs font-normal ml-1">单</span> -->
                        </div>
                        <div class="text-tx-secondary text-xs">
                            <span>较昨日</span>
                            <span class="up" v-if="workbenchData.today_statistic.yesterday_today_cooperation_rate >= 0">{{ `+${(workbenchData.today_statistic.yesterday_today_cooperation_rate * 10000 / 100).toFixed(2)}%` }}</span>
                            <span class="down" v-else>{{ `${(workbenchData.today_statistic.yesterday_today_cooperation_rate * 10000 / 100).toFixed(2) }%` }}</span>
                        </div>
                    </div>
                    <div class=" md:w-1/7">
                        <div class="leading-2.5">支付单数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.today_statistic.today_pay_order_num }}
                            <!-- <span class="text-xs font-normal ml-1">单</span> -->
                        </div>
                        <div class="text-tx-secondary text-xs">
                            <span>较昨日</span>
                            <span class="up" v-if="workbenchData.today_statistic.pay_order_num_rate >= 0">{{ `+${(workbenchData.today_statistic.pay_order_num_rate * 10000 / 100).toFixed(2)}%` }}</span>
                            <span class="down" v-else>{{ `${(workbenchData.today_statistic.pay_order_num_rate * 10000 / 100).toFixed(2) }%` }}</span>
                        </div>
                    </div>
                    <div class=" md:w-1/7">
                        <div class="leading-2.5">总支付费用</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.today_statistic.today_pay_order_sum }}
                            <!-- <span class="text-xs font-normal ml-1">单</span> -->
                        </div>
                        <div class="text-tx-secondary text-xs">
                            <span>较昨日</span>
                            <span class="up" v-if="workbenchData.today_statistic.pay_order_sum_rate >= 0">{{ `+${(workbenchData.today_statistic.pay_order_sum_rate * 10000 / 100).toFixed(2)}%` }}</span>
                            <span class="down" v-else>{{ `${(workbenchData.today_statistic.pay_order_sum_rate * 10000 / 100).toFixed(2) }%` }}</span>
                        </div>
                    </div>
                    <div class=" md:w-1/7">
                        <div class="leading-2.5">平台服务费</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.today_statistic.today_money_sum }}
                            <!-- <span class="text-xs font-normal ml-1">单</span> -->
                        </div>
                        <div class="text-tx-secondary text-xs">
                            <span>较昨日</span>
                            <span class="up" v-if="workbenchData.today_statistic.money_rate >= 0">{{ `+${(workbenchData.today_statistic.money_rate * 10000 / 100).toFixed(2)}%` }}</span>
                            <span class="down" v-else>{{ `${(workbenchData.today_statistic.money_rate * 10000 / 100).toFixed(2) }%` }}</span>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>
        <div class="lg:flex justify-between">
            <el-card class="!border-none mb-4 p-4 nav" shadow="never">
                <template #header>
                    <div class="mb-2.5">
                        <div class="card-title">平台数据</div>
                        <div class="text-tx-secondary text-xs flex items-center">
                            <span v-if="isPc" class="text-circle mr-2"></span>数据时间：{{ workbenchData.today.time }}
                        </div>
                    </div>
                </template>

                <div class="flex flex-wrap justify-between">
                    <div class=" md:w-1/4">
                        <div class="leading-2.5">总用户数</div>
                        <div class="text-4xl font-semibold">
                            {{ workbenchData.platform_data.reg_user_num > 10000 ? (workbenchData.platform_data.reg_user_num / 10000).toFixed(2): workbenchData.platform_data.reg_user_num}}
                            <span v-if="workbenchData.platform_data.reg_user_num > 10000">万</span>
                            <!-- <span class="text-xs font-normal ml-1">人</span> -->
                        </div>
                    </div>
                    <div class=" md:w-1/4">
                        <div class="leading-2.5">总渠道数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.platform_data.reg_channel_num }}
                            <!-- <span class="text-xs font-normal ml-1">人</span> -->
                        </div>
                    </div>
                    <div class=" md:w-1/4">
                        <div class="leading-2.5">总服务商数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.platform_data.reg_server_num }}
                            <!-- <span class="text-xs font-normal ml-1">人</span> -->
                        </div>
                    </div>
                    <div class=" md:w-1/4">
                        <div class="leading-2.5">总产品数</div>
                        <div class="text-4xl font-semibold">{{ workbenchData.platform_data.product_num }}
                            <!-- <span class="text-xs font-normal ml-1">种</span> -->
                        </div>
                    </div>
                </div>
            </el-card>
            <el-card class="!border-none mb-4 p-4 nav" shadow="never">
                <template #header>
                    <div class="mb-2.5">
                        <div class="card-title">支付数据</div>
                        <div class="text-tx-secondary text-xs flex items-center">
                            <span v-if="isPc" class="text-circle mr-2"></span>数据时间：{{ workbenchData.today.time }}
                        </div>
                    </div>
                </template>

                <div class="flex flex-wrap justify-between">
                    <el-popover
                        placement="top-start"
                        title="总支付单数"
                        :width="200"
                        trigger="hover"
                    >
                        <template #reference>
                            <div class=" md:w-1/3">
                                <div class="leading-2.5">总支付单数</div>
                                <div class="text-4xl font-semibold">
                                    {{ workbenchData.platform_data.cooperation_num > 10000 ? (workbenchData.platform_data.cooperation_num / 10000).toFixed(2): workbenchData.platform_data.cooperation_num}}
                                    <span v-if="workbenchData.platform_data.cooperation_num > 10000">万</span>
                                    <!-- <span class="text-xs font-normal ml-1">单</span> -->
                                </div>
                            </div>
                        </template>
                        <div v-for="(item,index) in workbenchData.platform_data.cooperation_data">{{ item.name }}：{{ item.total }}</div>
                    </el-popover>
                    <div class=" md:w-1/3">
                        <div class="leading-2.5">总支付费用</div>
                        <div class="text-4xl font-semibold">
                            {{ workbenchData.platform_data.cooperation_money > 10000 ? (workbenchData.platform_data.cooperation_money / 10000).toFixed(2): workbenchData.platform_data.cooperation_money}}
                            <span v-if="workbenchData.platform_data.cooperation_money > 10000">万</span><span class="text-xs font-normal">元</span></div>
                    </div>
                    <div class=" md:w-1/3">
                        <div class="leading-2.5">总平台服务费</div>
                        <div class="text-4xl font-semibold">
                            {{ workbenchData.platform_data.commission_money > 10000 ? (workbenchData.platform_data.commission_money / 10000).toFixed(2): workbenchData.platform_data.commission_money}}
                            <span v-if="workbenchData.platform_data.commission_money > 10000">万</span><span class="text-xs font-normal">元</span></div>
                    </div>
                </div>
            </el-card>
        </div>
        
        <div class="md:flex">
            <el-card class="flex-1 !border-none mb-4 p-3" shadow="never">
                <template #header>
                    <div class="mb-2.5">
                        <div class="card-title">每日核心数据</div>
                        <div class="text-tx-secondary text-xs flex items-center">
                            <span v-if="isPc" class="text-circle mr-2"></span>数据时间：{{ workbenchData.today.time }}
                        </div>
                    </div>
                </template>
                <div class="flex mb-2.5">
                    <div class="tab-btn w-20 h-8.5 leading-8 rounded-2xl ml-2.5" :class="{'tab-active':tabIndex == 0}" @click="onTab(0)">注册数据</div>
                    <div class="tab-btn w-20 h-8.5 leading-8 rounded-2xl ml-2.5" :class="{'tab-active':tabIndex == 1}" @click="onTab(1)">活跃数据</div>
                </div>
                <!-- <div class="city-flex">
                    <div v-for="(item,index) in city_arr" :key="index"
                        class="city-item" :class="{'city-active': area_index == index}" @click="onClick_area(item, index)">{{ item.area_short_name }}</div>
                </div> -->
                <el-form ref="formRef" class="mb-[-16px]" :inline="true" label-width="80px">
                    <el-form-item label="所属城市">
                        <el-select-v2
                            v-model="center_area"
                            filterable
                            clearable
                            :options="optionCity"
                            placeholder="请选择"
                            class="w-[140px]"
                            @change="center_day"
                        />
                    </el-form-item>
                </el-form>
                <div v-if="!isClose && !isPc" class="tip flex items-center ml-3.5 mr-4 h-9 rounded-sm pl-2.5">
                    <img class="w-4 h-4 mr-2" src="@/assets/images/home_tip.png" alt="">
                    <div>横向滑动查看更多，点击选择日期</div>
                    <div class="pl-10 ml-4" @click="onClose">
                        <img class="w-3 h-3 mr-2" src="@/assets/images/home_close.png" alt="">
                    </div>
                    
                </div>
                <div>
                    <v-charts
                        v-if="tabIndex == 0"
                        ref="vueChart"
                        :style="{height: `${isPc?280:175}px`}"
                        :option="workbenchData.visitorOption"
                        :autoresize="true"
                    />
                    <v-charts
                        v-if="tabIndex == 1"
                        ref="huoChart"
                        :style="{height: `${isPc?280:175}px`}"
                        :option="workbenchData.huoOption"
                        :autoresize="true"
                    />
                </div>
            </el-card>
        </div>
        <!-- <div class="md:flex">
            <el-card class="flex-1 !border-none mb-4 p-3" shadow="never">
                <template #header>
                    <div class="mb-2.5">
                        <div class="card-title">用户互动数据</div>
                        <div class="text-tx-secondary text-xs flex items-center">
                            <span v-if="isPc" class="text-circle mr-2"></span>数据时间：{{ workbenchData.today.time }}
                        </div>
                    </div>
                </template>
                <div>
                    <v-charts
                        ref="circleChart"
                        :style="{height: `${isPc?280:175}px`}"
                        :option="workbenchData.circleOption"
                        :autoresize="true"
                    />
                </div>
            </el-card>
        </div> -->
        <div class="md:flex">
            <el-card class="flex-1 !border-none mb-4 p-3" shadow="never">
                <template #header>
                    <div class="mb-2.5">
                        <div class="card-title">每日城市数据</div>
                        <div class="text-tx-secondary text-xs flex items-center">
                            <span v-if="isPc" class="text-circle mr-2"></span>数据时间：{{ workbenchData.today.time }}
                        </div>
                    </div>
                    <div class="mb-2.5 font-bold"><span class="mr-2.5">总计用户数：{{ total.user }}</span><span>总计渠道数：{{ total.channel }}</span></div>
                </template>
                <div>
                    <!-- <div class="city-flex">
                        <div v-for="(item,index) in city_arr" :key="index"
                        class="city-item" :class="{'city-active': city_index == index}" @click="onClick_city(index)">{{ item.area_short_name }}</div>
                    </div> -->
                    <el-form ref="formRef" class="mb-[-16px]" :inline="true" label-width="80px">
                        <el-form-item label="所属城市">
                            <el-select-v2
                                v-model="day_area"
                                filterable
                                clearable
                                :options="optionCity"
                                placeholder="请选择"
                                class="w-[140px]"
                                @change="select_day"
                            />
                        </el-form-item>
                        <el-form-item label="日期筛选">
                            <el-date-picker
                                v-model="day_arr"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                @change="areaDay"
                                :clearable="false"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-form>
                    <v-charts
                        ref="barChart"
                        :style="{height: `${isPc?280:175}px`}"
                        :option="workbenchData.barOption"
                        :autoresize="true"
                    />
                </div>
            </el-card>
        </div>

        <div class="md:flex">
            <el-card class="flex-1 !border-none mb-4 p-3" shadow="never">
                <template #header>
                    <div class="mb-2.5">
                        <div class="card-title">数据详情：默认当天实时数据</div>
                        <!-- <div class="text-tx-secondary text-xs flex items-center">
                            <span v-if="isPc" class="text-circle mr-2"></span>数据时间：{{ workbenchData.today.time }}
                        </div> -->
                    </div>
                </template>
                <div class="mb-5">
                    <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true" label-width="130px">
                        <el-form-item label="所属城市">
                            <el-select-v2
                                v-model="queryParams.area_id"
                                filterable
                                clearable
                                :options="optionCity"
                                placeholder="请选择"
                                class="w-[140px]"
                                @change="select_day"
                            />
                        </el-form-item>

                        <el-form-item label="订单状态">
                            <el-select
                                class="w-[140px]"
                                v-model="queryParams.reg_type"
                                placeholder="请选择"
                                clearable
                            >
                                <el-option label="全部" :value="0"/>
                                <el-option label="电梯投放" :value="1"/>
                                <el-option label="自然流量" :value="2"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="环比同比筛选">
                            <el-select
                                class="w-[140px]"
                                v-model="queryParams.date_type"
                                placeholder="请选择"
                                clearable
                            >
                                <el-option label="本日" :value="0" />
                                <el-option label="昨日" :value="1"/>
                                <el-option label="本周" :value="2"/>
                                <el-option label="上周" :value="3"/>
                                <el-option label="本月" :value="4"/>
                                <el-option label="上月" :value="5"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="日期" class="piker">
                            <el-date-picker
                                v-model="queryParams.date"
                                type="date"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择日期"
                            />
                        </el-form-item>
                        
                        <el-form-item class="w-80">
                            <el-button type="primary" @click="resetPage">查询</el-button>
                            <el-button @click="resetParams">重置</el-button>
                            <el-button type="primary" @click="download">下载</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div>
                    <el-table size="large" v-loading="pager.loading" :data="pager.lists" border>
                        <el-table-column label="用户分类" prop="name" min-width="160" />
                        <el-table-column label="访问用户数" prop="count" min-width="160" />
                        <el-table-column label="环比/同比" prop="name" min-width="160">
                            <template #default="{ row }">
                                <div v-if="row.name != '合计'">
                                    <div class="flex items-center">
                                        <div>环比</div>
                                        <el-icon color="#FF6900"><Top /></el-icon>
                                        <div>{{ row.fangwen_huanbi_rate }}%</div>
                                    </div>
                                    <div class="flex items-center">
                                        <div>同比</div>
                                        <el-icon color="#D81313"><Bottom /></el-icon>
                                        <div>{{ row.fangwen_tongbi_rate }}%</div>
                                    </div>
                                </div>
                                <div v-else>-</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="日平均来访次数" prop="avg_times" min-width="160" />
                        <!-- <el-table-column label="平均停留时长（分/秒）" prop="name" min-width="160" /> -->
                        <el-table-column label="提需求用户数" prop="demand_user" min-width="160" />
                        <el-table-column label="环比/同比" prop="name" min-width="160" >
                            <template #default="{ row }">
                                <div class="flex items-center">
                                    <div>环比</div>
                                    <el-icon color="#FF6900"><Top /></el-icon>
                                    <div>{{ row.demand_user_huanbi_rate }}%</div>
                                </div>
                                <div class="flex items-center">
                                    <div>同比</div>
                                    <el-icon color="#D81313"><Bottom /></el-icon>
                                    <div>{{ row.demand_user_tongbi_rate }}%</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="提需求数" prop="demand_count" min-width="160" />
                        <el-table-column label="环比/同比" prop="name" min-width="160" >
                            <template #default="{ row }">
                                <div class="flex items-center">
                                    <div>环比</div>
                                    <el-icon color="#FF6900"><Top /></el-icon>
                                    <div>{{ row.demand_count_huanbi_rate }}%</div>
                                </div>
                                <div class="flex items-center">
                                    <div>同比</div>
                                    <el-icon color="#D81313"><Bottom /></el-icon>
                                    <div>{{ row.demand_count_tongbi_rate }}%</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="需求通过数" prop="demand_success" min-width="160" />
                        <el-table-column label="环比/同比" prop="name" min-width="160" >
                            <template #default="{ row }">
                                <div class="flex items-center">
                                    <div>环比</div>
                                    <el-icon color="#FF6900"><Top /></el-icon>
                                    <div>{{ row.demand_success_huanbi_rate }}%</div>
                                </div>
                                <div class="flex items-center">
                                    <div>同比</div>
                                    <el-icon color="#D81313"><Bottom /></el-icon>
                                    <div>{{ row.demand_success_tongbi_rate }}%</div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script lang="ts" setup name="workbench">
import { getWorkbench, statistic, statisticUserAndChannel, huoyueData, monthCoreData, allStatistics, downAllStatistics } from '@/api/app'
import { usePaging } from '@/hooks/usePaging';
import useAppStore from '@/stores/modules/app'
import vCharts from 'vue-echarts'
import configs from '@/config'

const center_area = ref('')
const center_day = (val:any) => {
    console.log(val)
    console.log(val == undefined)
    console.log(val == 'undefined')
    if (val == undefined) {
        center_area.value = '';
    }
    today_area.value = center_area.value;
    getHuoyueData();
    getMonthCoreData();
}

const day_area = ref('')
const day_arr:any = ref('')
const areaDay = (e:any) => {
    console.log(e)
    console.log(day_arr.value)
    getCityData()
}
const select_day = (val:any) => {
    console.log(val)
    console.log(val == undefined)
    console.log(val == 'undefined')
    if (val == undefined) {
        day_area.value = '';
    }
   
    let arr_index:any = ''
    city_arr.value.forEach((item:any, index:number) => {
        if (item.area_id == day_area.value ) {
            console.log(index)
            arr_index = index;
        }
    })

    workbenchData.barOption.xAxis.data = []
    workbenchData.barOption.series[0].data = []
    workbenchData.barOption.series[1].data = []

    workbenchData.barOption.xAxis.data = city_arr.value[arr_index].dateArr
    workbenchData.barOption.series[0].data = city_arr.value[arr_index].totalArr
    workbenchData.barOption.series[1].data = city_arr.value[arr_index].channelArr
    barChart.value.setOption({
        ...workbenchData.barOption
    })
}


const vueChart = ref();
const circleChart = ref()
const barChart = ref();
const huoChart = ref();

const queryParams = reactive({
    area_id: '',
    reg_type: '',
    date_type: '',
    date: ''
})
const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: allStatistics,
    params: queryParams
})

const baseUrl = `${import.meta.env.VITE_URL_LINK || ''}`
const download = async () => {
    let url = `${baseUrl}/api/test/downAllStatistics?page_no=1&page_size=15&area_id=${queryParams.area_id}&reg_type=${queryParams.reg_type}&date_type=${queryParams.date_type}&date=${queryParams.date}`
    console.log(url)
    triggerDownload(url)
}

const  triggerDownload =(url:any, filename?:any) => {
  const link = document.createElement('a');
  link.href = url;
  link.download = filename || 'downloaded-file';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

const useApp = useAppStore()
const optionCity:any = ref([])
const select_data = () => {
    optionCity.value = [{area_id: '',area_short_name: '全部',label: '全部',value:''}].concat(useApp.optionCity).concat([{area_id: '999',area_short_name: '其他城市',label: '其他城市',value:'999'}]);
}
select_data()


// 获取城市数据
const city_index = ref(0)
const onClick_city = (index: number) => {
    if (city_index.value == index) {
        return false;
    }
    city_index.value = index;
    workbenchData.barOption.xAxis.data = []
    workbenchData.barOption.series[0].data = []
    workbenchData.barOption.series[1].data = []

    workbenchData.barOption.xAxis.data = city_arr.value[city_index.value].dateArr
    workbenchData.barOption.series[0].data = city_arr.value[city_index.value].totalArr
    workbenchData.barOption.series[1].data = city_arr.value[city_index.value].channelArr
    barChart.value.setOption({
        ...workbenchData.barOption
    })
}
const city_arr:any = ref([])
const total = reactive({
    user: 0,
    channel: 0
})
const getCityData = async () => {
    let params = {
        start: day_arr.value[0] || '',
        end: day_arr.value[1] || ''
    }
    const res = await statisticUserAndChannel(params)
    console.log('========')
    console.log(res)
    day_arr.value = [res.start_time, res.end_time]
    total.user = res.total_user;
    total.channel = res.total_channel;
    let arr = generateDateRange(res.start_time, res.end_time)
    // console.log(arr)
    // 日期
    // arr.map((item) => {
        // 多个城市
        res.list.map((itemC:any) => {
            // let totalArr:any = [];
            // let channelArr:any = [];
            // let dateArr:any = []
            itemC.totalArr = []
            itemC.channelArr = []
            itemC.dateArr = []
            arr.map((item) => {
                let obj = {
                    user_total_count: 0,
                    channel_total_count: 0,
                    value: 0,
                    date: item
                }
                // 城市里面的日期
                itemC.data.map((itemD:any)=>{
                    if ( itemD.dates ==  item) {
                        obj.user_total_count = itemD.user_total_count;
                        obj.channel_total_count = itemD.channel_total_count;
                        obj.value = itemD.user_total_count
                    }
                })
                itemC.totalArr.push(obj)
                itemC.channelArr.push({...obj, value: obj.channel_total_count})
                itemC.dateArr.push(obj.date.split('-')[2])
            })
            
        })

    // })
    console.log('newnew')
    // console.log(arr)
    // console.log(res.list)
    city_arr.value = res.list;


    workbenchData.barOption.xAxis.data = []
    workbenchData.barOption.series[0].data = []
    workbenchData.barOption.series[1].data = []

    workbenchData.barOption.xAxis.data = res.list[city_index.value].dateArr
    workbenchData.barOption.series[0].data = res.list[city_index.value].totalArr
    workbenchData.barOption.series[1].data = res.list[city_index.value].channelArr
    barChart.value?.setOption({
        ...workbenchData.barOption
    })

    // 圈子的数据统计
    let circle_date:any = [];
    let dynamic_count_arr:any = [];
    let dynamic_user_arr:any = [];
    let im_count_arr:any = [];
    let im_user_arr:any = [];
    console.log(res.behavior_list)
    res.behavior_list.map((item:any) => {
        circle_date.push(item.dates.split('-')[2])
        dynamic_count_arr.push({...item, value: item.dynamic_count})
        dynamic_user_arr.push(item.dynamic_user)
        im_count_arr.push(item.im_count)
        im_user_arr.push(item.im_user)
    })

    workbenchData.circleOption.xAxis.data = []
    workbenchData.circleOption.series[0].data = []
    workbenchData.circleOption.series[1].data = []
    workbenchData.circleOption.series[2].data = []
    workbenchData.circleOption.series[3].data = []

    workbenchData.circleOption.xAxis.data = circle_date;
    workbenchData.circleOption.series[0].data = dynamic_count_arr
    workbenchData.circleOption.series[1].data = dynamic_user_arr
    workbenchData.circleOption.series[2].data = im_count_arr
    workbenchData.circleOption.series[3].data = im_user_arr
    circleChart.value?.setOption({
        ...workbenchData.circleOption
    })
}
getCityData()

const area_index = ref(0)
const today_area = ref('')
const onClick_area = (item:any, index: number) => {
    area_index.value = index;
    today_area.value = item.area_id;
    console.log(item)
    getHuoyueData();
    getMonthCoreData();
}

// 活跃数据
const getHuoyueData = async () => {
    const res = await await huoyueData({
        area_id: today_area.value
    })
    console.log('huoyueDatahuoyueData')
    console.log(res)
    let arr = generateDateRange(res.start_date, res.end_date)

    let newArr:any = []
    let dateArr:any = []

    arr.map((item) => {
        let obj = {
            count: 0,
            date: item,
            value: 0
        }
        res.return_data.map((itemC: any) => {
            if (item == itemC.dates) {
                obj.count = itemC.count;
                obj.value = itemC.count;
            }
        })
        newArr.push(obj)
        dateArr.push(obj.date.split('-')[2])
    })

    workbenchData.huoOption.xAxis.data = []
    workbenchData.huoOption.series[0].data = []

    workbenchData.huoOption.xAxis.data = dateArr
    workbenchData.huoOption.series[0].data = newArr
    
     huoChart.value?.setOption({
        ...workbenchData.huoOption
    })
    
}
getHuoyueData()

const isPc = ref(true)
const isClose = ref(false)
const onClose = () => {
    window.localStorage.setItem('isClose', 'true')
    isClose.value = true;
}
const tabIndex = ref(0)
const onTab = (num:number) => {
    if (num == tabIndex.value) {
        return false
    }
    tabIndex.value = num;
}
// 表单数据
const workbenchData: any = reactive({
    today_statistic: {
        today_reg_user_num: 0, // 今天注册用户数
        yesterday_today_reg_user_rate: 0.01, // 较昨日 注册用户数据比例 (实际值):比如：0.01
        today_ac_user_num: '', // 今天活跃用户数
        yesterday_today_ac_user_rate: '', // 较昨日 活跃用户数数据比例(实际值):比如：0.01
        today_ac_channel_num: '', // 今天活跃渠道数
        yesterday_today_ac_channel_rate: '', // 较昨日 活跃渠道数数据比例(实际值):比如：0.01
        today_cooperation_num: '', // 合作单数
        yesterday_today_cooperation_rate: '', // 较昨日 合作单数数据比例(实际值):比如：0.01，
        today_pay_order_num: '', // 支付单数
        pay_order_num_rate: '',
        today_pay_order_sum: '',
        pay_order_sum_rate: '',
        today_money_sum: '',
        money_rate: ''
    },
    platform_data: {
        reg_user_num: 0, // 总注册用户数
        reg_channel_num: 0, // 总渠道数
        reg_server_num: 0, // 总服务商数
        product_num: 0, // 总产品数
        cooperation_num: 0, // 总合作单数
        cooperation_money: 0 , // 总合作订单金额
        commission_money: 0, // 总平台收佣
        cooperation_data: []
    },
    month_core_data: {
        start_date: '',
        end_date: '',
        return_data: []
    },
    version: {
        version: '', // 版本号
        website: '', // 官网
        based: '',
        channel: {
            gitee: '',
            website: ''
        }
    },
    support: [],
    today: {}, // 今日数据
    menu: [], // 常用功能
    visitor: [], // 访问量
    article: [], // 文章阅读量

    visitorOption: {
        xAxis: {
            type: 'category',
            data: [0]
        },
        yAxis: {
            type: 'value'
        },
        legend: {
            show: true,
            orient: 'horizontal',
            x: 'center',
            y: 'bottom',
            itemHeight: 3,
            bottom: '0',
            data: ['新增注册用户数', '新增小程序注册数', '新增APP注册数']
        },
        itemStyle: {
            // 点的颜色。
            color: 'red'
        },
        tooltip: {
            trigger: 'axis',
            confine: true,
            backgroundColor: 'rgba(255,255,255,1)',
            textStyle: {
                color: '#333333'
            },
            label:{
               
            },
            formatter: (params: any) => {
                // console.log(params)
                let str = `${params[0].data.date}号</br>`;
                params.forEach((item:any)=>{
                    str += `${item.marker}${item.seriesName}&nbsp;&nbsp;&nbsp;&nbsp;   ${item.value}</br>`
                })
                return params.length > 0 ? str: ''
                // return `${params[0].data.date}号</br>
                //         ${params[0].marker}${params[0].seriesName}&nbsp;&nbsp;&nbsp;   ${params[0].value}</br>
                //         ${params[1].marker}${params[1].seriesName}   ${params[1].value}</br>
                //         ${params[2].marker}${params[2].seriesName}&nbsp;&nbsp;&nbsp;   ${params[2].value}</br>`
            },
        },
        grid: {
            left: "3%",
            top: "10%",
            right: "3%",
            bottom: "15%",
        },

        dataZoom:[],
        series: [
            {
                name: '新增注册用户数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                itemStyle: { color: '#809BF3' }
            },
            {
                name: '新增小程序注册数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                itemStyle: { color: '#FF6900' }
            },
            {
                name: '新增APP注册数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                itemStyle: { color: '#56D99F' }
            }
        ]
    },
    // 圈子数据
    circleOption: {
        xAxis: {
            type: 'category',
            data: [0]
        },
        yAxis: {
            type: 'value'
        },
        legend: {
            show: true,
            orient: 'horizontal',
            x: 'center',
            y: 'bottom',
            itemHeight: 3,
            bottom: '0',
            data: ['动态发布数', '动态发布人数', '发送人数', '接收人数']
        },
        itemStyle: {
            // 点的颜色。
            color: 'red'
        },
        tooltip: {
            trigger: 'axis',
            confine: true,
            backgroundColor: 'rgba(255,255,255,1)',
            textStyle: {
                color: '#333333'
            },
            label:{
               
            },
            formatter: (params: any) => {
                // console.log(params)
                let str = `${params[0].data.date}号</br>`;
                params.forEach((item:any)=>{
                    str += `${item.marker}${item.seriesName}&nbsp;&nbsp;&nbsp;&nbsp;   ${item.value}</br>`
                })
                return params.length > 0 ? str: ''
                // return `${params[0].data.dates}号</br>
                //         ${params[0].marker}${params[0].seriesName}&nbsp;&nbsp;&nbsp;   ${params[0].value}</br>
                //         ${params[1].marker}${params[1].seriesName}   ${params[1].value}</br>
                //         ${params[2].marker}${params[2].seriesName}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   ${params[2].value}</br>
                //         ${params[3].marker}${params[3].seriesName}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   ${params[3].value}</br>`
            },
        },
        grid: {
            left: "5%",
            top: "10%",
            right: "3%",
            bottom: "15%",
        },

        dataZoom:[],
        series: [
            {
                name: '动态发布数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                itemStyle: { color: '#56D99F' }
            },
            {
                name: '动态发布人数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                itemStyle: { color: '#FF6900' }
            },
            {
                name: '发送人数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                itemStyle: { color: '#809BF3' }
            },
            {
                name: '接收人数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                // itemStyle: { color: '#56D99F' }
            }
        ]
    },
    // 活跃数据
    huoOption: {
        xAxis: {
            type: 'category',
            data: [0]
        },
        yAxis: {
            type: 'value'
        },
        legend: {
            show: true,
            orient: 'horizontal',
            x: 'center',
            y: 'bottom',
            itemHeight: 3,
            bottom: '0',
            data: ['活跃用户数']
        },
        itemStyle: {
            // 点的颜色。
            color: 'red'
        },
        tooltip: {
            trigger: 'axis',
            confine: true,
            backgroundColor: 'rgba(255,255,255,1)',
            textStyle: {
                color: '#333333'
            },
            label:{
               
            },
            formatter: (params: any) => {
                // console.log(params)
                let str = `${params[0].data.date}号</br>`;
                params.forEach((item:any)=>{
                    str += `${item.marker}${item.seriesName}&nbsp;&nbsp;&nbsp;&nbsp;   ${item.value}</br>`
                })
                return params.length > 0 ? str: ''
                // return `${params[0].data.date}号</br>
                //         ${params[0].marker}${params[0].seriesName}  ${params[0].value}</br>`
            },
        },
        grid: {
            left: "3%",
            top: "10%",
            right: "3%",
            bottom: "15%",
        },

        dataZoom:[],
        series: [
            {
                name: '活跃用户数',
                data: [0],
                type: 'line',
                smooth: true,
                symbol: 'none',
                itemStyle: { color: '#809BF3' }
            }
        ]
    },
    // 柱状图
    barOption: {
        xAxis: {
            type: 'category',
            data: [0]
        },
        yAxis: {
            type: 'value',
            minInterval: 1,
        },
        legend: {
            show: true,
            orient: 'horizontal',
            x: 'center',
            y: 'bottom',
            itemHeight: 3,
            bottom: '0',
            data: ['新增用户数', '新增渠道数']
        },
        itemStyle: {
            // 点的颜色。
            color: 'red'
        },
        tooltip: {
            trigger: 'axis',
            confine: true,
            backgroundColor: 'rgba(255,255,255,1)',
            textStyle: {
                color: '#333333'
            },
            label:{
               
            },
            formatter: (params: any) => {
                // console.log(params)
                let str = `${params[0].data.date}号</br>`;
                params.forEach((item:any)=>{
                    str += `${item.marker}${item.seriesName}&nbsp;&nbsp;&nbsp;&nbsp;   ${item.value}</br>`
                })
                return params.length > 0 ? str: ''
                // return `${params[0].data.date}号</br>
                //         ${params[0].marker}${params[0].seriesName}   ${params[0].value}</br>
                //         ${params[1].marker}${params[1].seriesName}   ${params[1].value}</br>`
            },
        },
        grid: {
            left: "3%",
            top: "10%",
            right: "3%",
            bottom: "15%",
        },

        dataZoom:[],
        series: [
            {
                name: '新增用户数',
                data: [0],
                type: 'bar',
                smooth: true,
                symbol: 'none',
                itemStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: '#FF6900'
                        }, {
                            offset: 1,
                            color: '#FFFFFF'
                        }]
                    }
                }
            },
            {
                name: '新增渠道数',
                data: [0],
                type: 'bar',
                smooth: true,
                symbol: 'none',
                itemStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: '#7A94E8'
                        }, {
                            offset: 1,
                            color: '#FFFFFF'
                        }]
                    }
                }
            }
        ]
    }
})

//注册数据
const getMonthCoreData = async () => {
    const res = await await monthCoreData({
        area_id: today_area.value
    })
    workbenchData.month_core_data = res.month_core_data;
    let arr = generateDateRange(res.month_core_data.start_date, res.month_core_data.end_date)
    // console.log(arr)
    let newArr:any = []
    let dateArr:any = []
    let appArr:any = []
    let miniArr:any = []
    let totalArr:any = []

    arr.map((item) => {
        let obj = {
            app_reg_count: 0,
            date: item,
            mini_reg_count: 0,
            total_reg_count: 0,
            value: 0
        }
        res.month_core_data.return_data.map((itemC: any) => {
            if (item == itemC.date) {
                obj.app_reg_count = itemC.app_reg_count;
                obj.mini_reg_count = itemC.mini_reg_count
                obj.total_reg_count = itemC.total_reg_count
                obj.value = itemC.total_reg_count
            }
        })
        newArr.push(obj)
        dateArr.push(obj.date.split('-')[2])
        appArr.push({...obj, value: obj.app_reg_count})
        miniArr.push({...obj, value: obj.mini_reg_count})
        totalArr.push({...obj, value: obj.total_reg_count})
    })

    workbenchData.visitorOption.xAxis.data = []
    workbenchData.visitorOption.series[0].data = []
    workbenchData.visitorOption.series[1].data = []
    workbenchData.visitorOption.series[2].data = []

    workbenchData.visitorOption.xAxis.data = dateArr
    workbenchData.visitorOption.series[0].data = newArr
    workbenchData.visitorOption.series[1].data = miniArr
    workbenchData.visitorOption.series[2].data = appArr

    nextTick(()=>{
        if (vueChart.value) {
            const dataLen = dateArr.length
            const lastIndex = dataLen - 1
            
            // 高亮最后一个点
            vueChart.value.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: lastIndex
            })
            
            // 显示 tooltip
            vueChart.value.dispatchAction({
                type: 'showTip',
                seriesIndex: 0,
                dataIndex: lastIndex
            })
        }
    })
}

const area_id = ref('')
// 获取工作台主页数据
const getStatistic = async () => {
    const res = await statistic({
        area_id: area_id.value
    })
    // console.log(res)
    workbenchData.today_statistic = res.today_statistic;
    workbenchData.platform_data = res.platform_data;
}

const generateDateRange = (startDate:any, endDate:any) => {
    let dateArray = [];
    let currentDate = new Date(startDate);
    let endDateObj = new Date(endDate);
 
    // 确保循环在到达结束日期之前停止（包括结束日期）
    while (currentDate <= endDateObj) {
        // 使用 toISOString().split('T')[0] 来格式化日期为 YYYY-MM-DD
        dateArray.push(currentDate.toISOString().split('T')[0]);
        // 增加一天
        currentDate.setDate(currentDate.getDate() + 1);
    }
 
    return dateArray;
}
const onChange = (val:any) => {
    console.log(val)
    area_id.value == val;
    getStatistic();
}
getStatistic()
const getData = () => {
    getWorkbench()
        .then((res: any) => {
            workbenchData.version = res.version
            workbenchData.today = res.today
            workbenchData.menu = res.menu
            workbenchData.visitor = res.visitor
            workbenchData.support = res.support
        })
        .catch((err: any) => {
            console.log('err', err)
        })
}

const isMobile = () => {
    const userAgentInfo = navigator.userAgent;
    const mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
     const mobileFlag = mobileAgents.some((mobileAgent) => {
        return userAgentInfo.indexOf(mobileAgent) > 0;
    });

    return mobileFlag;
}
const scrollY = ref(0);

const handleScroll = (e:any) => {
    console.log('当前滚动位置'+e)
    // scrollY.value = window.scrollY;
    // 你可以在这里添加其他滚动事件处理逻辑
    // console.log('当前滚动位置:', scrollY.value);
};
onMounted(() => {
    if (window.localStorage.getItem('isClose')) {
        isClose.value = true;
    }
    if (isMobile()) {
        // 移动端的图表变化
        isPc.value = false;
        workbenchData.visitorOption.dataZoom = [
            {
                type: 'slider',
                show: false,
                start: 0,
                end: 25,
                handleSize: 8,
                handleColor: {
                    color: '#DCE2E8'
                },
                xAxisIndex: [0],
                filterMode: 'filter'
            },
            {
                zoomOnMouseWheel: false,
                type: "inside",
            },
        ];
        workbenchData.visitorOption.grid = {
            left: "12%",
            top: "10%",
            right: "3%",
            bottom: "12%",
        }
        workbenchData.visitorOption.tooltip.backgroundColor = 'rgba(74, 70, 67, 1)';
        workbenchData.visitorOption.tooltip.textStyle.color = '#FFFFFF';
        workbenchData.visitorOption.legend.show = false;
        
        workbenchData.barOption.dataZoom = [
            {
                type: 'slider',
                show: false,
                start: 0,
                end: 25,
                handleSize: 8,
                handleColor: {
                    color: '#DCE2E8'
                },
                xAxisIndex: [0],
                filterMode: 'filter'
            },
            {
                zoomOnMouseWheel: false,
                type: "inside",
            },
        ];
        workbenchData.barOption.grid = {
            left: "12%",
            top: "10%",
            right: "3%",
            bottom: "12%",
        }
        workbenchData.barOption.tooltip.backgroundColor = 'rgba(74, 70, 67, 1)';
        workbenchData.barOption.tooltip.textStyle.color = '#FFFFFF';
        workbenchData.barOption.legend.show = false;

        workbenchData.huoOption.dataZoom = [
            {
                type: 'slider',
                show: false,
                start: 0,
                end: 25,
                handleSize: 8,
                handleColor: {
                    color: '#DCE2E8'
                },
                xAxisIndex: [0],
                filterMode: 'filter'
            },
            {
                zoomOnMouseWheel: false,
                type: "inside",
            },
        ];
        workbenchData.huoOption.grid = {
            left: "12%",
            top: "10%",
            right: "3%",
            bottom: "12%",
        }
        workbenchData.huoOption.tooltip.backgroundColor = 'rgba(74, 70, 67, 1)';
        workbenchData.huoOption.tooltip.textStyle.color = '#FFFFFF';
        workbenchData.huoOption.legend.show = false;
    }
    getData()
    getMonthCoreData()
    // getLists()
    window.addEventListener('scroll', handleScroll);
})
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});
</script>

<style lang="scss" scoped>
.workbench{
    ::v-deep .el-card__header{
        border: none;
        padding: 0;
    }
    ::v-deep .el-card__body{
        border: none;
        padding: 0;
    }
    ::v-deep .el-table th{
        background-color: #FFFFFF !important;
    }
    .no-pb{
        ::v-deep .el-card__header{
            padding-bottom: 0;
       
        }
    }
    .card-title{
        // font-size: 12px;
        color: #171717;
        font-weight: bold;
    }
    .text-circle{
        display: inline-block;
        width: 4px;
        height: 4px;
        border-radius: 50%; 
        background: #FF6900;
    }
    .up{
       color: #13D897; 
    }
    .down{
        color: #D81313;
    }
    .nav{
        width: 49.5% !important;
    }
    @media (max-width: 575px) {
        .nav {
            width: 100% !important;
        }
    }
    .tab-btn{
        background: #FFFFFF;
        color: #666666;
        border: 1px solid #DBD9D9;
        text-align: center;
        cursor: pointer;
    }
    .tab-active{
        background: #FF6900;
        color: #FFFFFF;
        border:none;
    }
    .tip{
        background: #FAFAFA;
        color: #666666;
    }
    .city-flex{
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        .city-item{
            width: 80px;
            height: 32px;
            font-size: 12px;
            line-height: 30px;
            color: #999999;
            font-weight: 500;
            text-align: center;
            border-radius: 8px;
            border: 1px solid #DBD9D9;
            margin-right: 8px;
            margin-bottom: 8px;
            cursor: pointer;
        }
        .city-active{
            color: #333333;
            background-color: #E7E7E7;
        }
    }
}

</style>
